<template>
	<div>
		<el-dialog title="消费奖励积分" :visible.sync="dialogVisible" width="650px" :close-on-click-modal="false" @close="close">
			<div v-loading="loading">
				<!-- tips -->
				<div class="tips">
					<el-tag type="warning" style="width:100%">
						<i class="el-icon-warning" />
						&nbsp;会员充值并非消费, 所以顾客微信充值余额并不会触发此规则。
					</el-tag>
				</div>

				<!-- 表单 -->
				<div class="form">
					<el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
						<el-form-item label="功能开关：" class="use-limit-box"><el-switch v-model="form.enableConsumeBonus" /></el-form-item>

						<!-- 启用设置 -->
						<el-collapse-transition>
							<div v-if="form.enableConsumeBonus">
								<!-- 积分系数 -->
								<el-form-item label="积分系数：" class="use-limit-box form-item-bottom">
									<span>每消费&nbsp;&nbsp;</span>
									<el-form-item prop="bonusRatio" style="display:inline-block">
										<el-input v-model="form.bonusRatio" maxlength="7" class="input-append-200">
											<template slot="append">
												元
											</template>
										</el-input>
										&nbsp;&nbsp;奖励一个积分
									</el-form-item>
								</el-form-item>

								<!-- 积分上限 -->
								<el-form-item label="积分上限：" class="use-limit-box form-item-bottom">
									<div><el-radio v-model="form.bonusLimitRadio" :label="0">无上限</el-radio></div>
									<div>
										<el-radio v-model="form.bonusLimitRadio" :label="1">单次最多获取积分&nbsp;&nbsp;</el-radio>
										<el-form-item prop="bonusLimit" style="display:inline-block">
											<el-input v-model="form.bonusLimit" :disabled="form.bonusLimitRadio === 0" maxlength="7" class="input-append-200">
												<template slot="append">
													个
												</template>
											</el-input>
										</el-form-item>
									</div>
								</el-form-item>

                <!-- 退款积分 -->
                <el-form-item label="退款积分：" class="use-limit-box">
                  <el-radio v-model="form.reduceAfterRefund" :label="true">消费退款后回收已奖励的积分</el-radio>
                  <br>
                  <el-radio v-model="form.reduceAfterRefund" :label="false">不回收积分</el-radio>
                </el-form-item>
              </div>
            </el-collapse-transition>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" round @click="hide">取 消</el-button>
        <el-button size="small" round type="primary" :loading="loading" @click="handleSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { validatePositiveInt } from '@/utils/validate.js';
import { updatePointsConfig } from '@/api/points';
export default {
  data() {
    /**
       * 表单校验方法
       */
    const validateBonusRatio = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入金额'))
      } else if (!validatePositiveInt(value)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }
    const validateBonusLimit = (rule, value, callback) => {
      if (this.form.bonusLimitRadio === 0) {
        callback()
      } else if (value === '') {
        callback(new Error('请输入单次最多获取积分'))
      } else if (!validatePositiveInt(value)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }
    return {
      /**
         * 表单校验字段
         */
      rules: {
        bonusRatio: [
          {
            required: true,
            validator: validateBonusRatio,
            trigger: ['blur', 'change']
          }
        ],
        bonusLimit: [
          {
            required: true,
            validator: validateBonusLimit,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      resolve: null,
      reject: null,
      // 状态
      dialogVisible: false,
      loading: false,
      checkList:'',
      // 数据
      form: {
        bonusLimit: null
      }
    }
  },
  watch: {
    form: {
      handler: function(val) {
        this.$nextTick(() => {
          if (val.enableConsumeBonus && val.bonusLimitRadio === 0) {
            this.$refs.form.clearValidate(['bonusLimit'])
          }
        })
      },
      deep: true
    }
  },
  methods: {
    open(data) {
      this.form = this.resetData(data)
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

		// 格式化数据
		resetData(data) {
			const form = Object.assign({}, data);
			if (form.bonusLimit === 0) {
				form.bonusLimit = '';
				form.bonusLimitRadio = 0;
			} else {
				form.bonusLimitRadio = 1;
			}
			return form;
		},

		show() {
			this.dialogVisible = true;
		},

		close() {
			this.loading = false;
		},

		hide() {
			this.resolve = null;
			this.reject = null;
			this.dialogVisible = false;
		},

		handleSubmit() {
			this.$refs.form.validate(valid => {
				if (valid) {
					const params = {};
					if (this.form.enableConsumeBonus) {
						params.enableConsumeBonus = this.form.enableConsumeBonus;
						params.bonusRatio = this.form.bonusRatio * 100;
						params.reduceAfterRefund = this.form.reduceAfterRefund;
						if (this.form.bonusLimitRadio === 0) {
							params.bonusLimit = 0;
						} else {
							params.bonusLimit = this.form.bonusLimit;
						}
					} else {
						params.enableConsumeBonus = this.form.enableConsumeBonus;
					}
					params.id = this.form.id;
					this.loading = true;
					updatePointsConfig(params)
						.then(res => {
							this.$notify({
								title: '成功',
								message: '保存成功',
								type: 'success',
								duration: 2000,
								offset: 40
							});
							this.$root.$emit('pointsResetConfig', res.data);
							this.hide();
						})
						.finally(() => {
							this.loading = false;
						});
				}
			});
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.form {
	margin-top: 20px;
	.input-append-200 {
		width: 200px;
	}
	/* margin-bottom 0px */
	.form-item-bottom {
		margin-bottom: 0;
	}
}
</style>
